package com.xh.bussiness.textbook.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.google.common.base.CaseFormat;
import com.google.common.base.Joiner;
import com.xh.bussiness.permission.model.UserArea;
import com.xh.bussiness.permission.service.IUserAreaService;
import com.xh.bussiness.teachbook.bean.request.TeachingBookModuleDetailRequest;
import com.xh.bussiness.teachbook.bean.request.TeachingBookModuleRequest;
import com.xh.bussiness.teachbook.bean.request.TeachingBookPracticeContentRequest;
import com.xh.bussiness.teachbook.bean.request.TeachingBookPracticeRequest;
import com.xh.bussiness.teachbook.constant.TeachingBookConstant;
import com.xh.bussiness.teachbook.model.TeachingBookTemplate;
import com.xh.bussiness.teachbook.service.ITeachingBookTemplateService;
import com.xh.bussiness.textbook.bean.dto.TextbookDto;
import com.xh.bussiness.textbook.bean.dto.TextbookInfoDto;
import com.xh.bussiness.textbook.bean.request.AddTextbookRequest;
import com.xh.bussiness.textbook.bean.request.QueryTextbookRequest;
import com.xh.bussiness.textbook.dao.TextbookMapper;
import com.xh.bussiness.textbook.model.*;
import com.xh.bussiness.textbook.service.*;
import com.xh.bussiness.tiku.bean.dto.QuestionDto;
import com.xh.bussiness.tiku.model.BookChapter;
import com.xh.bussiness.tiku.service.IBookChapterService;
import com.xh.bussiness.tiku.service.IQuestionService;
import com.xh.core.bean.XhPage;
import com.xh.core.exception.XhException;
import com.xh.core.service.impl.BaseServiceImpl;
import com.xh.core.util.DateUtils;
import com.xh.core.util.UserUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 讲义相关
 * </p>
 *
 * @author Pitt zhang
 * @since 2019/9/26
 */
@Service
public class TextbookServiceImpl extends BaseServiceImpl<TextbookMapper, Textbook> implements ITextbookService {

    @Autowired
    private ITeachingBookTemplateService teachingBookTemplateService;
    @Autowired
    private ITextbookModuleService textbookModuleService;
    @Autowired
    private ITextbookPracticeService textbookPracticeService;
    @Autowired
    private ITextbookPracticeContentService textbookPracticeContentService;
    @Autowired
    private ITextbookModuleDetailService textbookModuleDetailService;
    @Autowired
    private IQuestionService questionService;
    @Autowired
    private IBookChapterService bookChapterService;
    @Autowired
    private IUserAreaService userAreaService;

    //连接器
    private static final Joiner joiner = Joiner.on(",").skipNulls();

    Logger log = LoggerFactory.getLogger(TextbookServiceImpl.class);

    @Override
    public String addTextbook(AddTextbookRequest bean) {
        Textbook tb;
        if (!StringUtils.isEmpty(bean.getId())) {
            tb = this.getById(bean.getId());
            if (StringUtils.isEmpty(tb.getUniqueKey())) {
                tb.setUniqueKey(bean.getUniqueKey());
                this.update(tb);
            }
            //删除讲义相关内容
            deleteTextbookByDetailById(bean.getId());
        } else {
            tb = new Textbook();
            //适用阶段
            if (!CollectionUtils.isEmpty(bean.getApplyLevel())) {
                String appLevels = joiner.join(bean.getApplyLevel());
                tb.setApplyLevel(appLevels);
            }
            //添加讲义
            org.springframework.beans.BeanUtils.copyProperties(bean, tb, "applyLevel");
            tb.setYear(DateUtils.getDateField(new Date(), Calendar.YEAR));
            this.insert(tb);

        }
        if (tb == null) {
            throw new XhException("讲义数据不存在");
        }
        //用于保存箐优网试题
        Map<String, QuestionDto> duplicateQuesIdMapValid = new HashMap<>();
        //讲义模块详情
        List<TeachingBookModuleRequest> moduleRequestList = bean.getTextbookModuleRequestList();
        for (TeachingBookModuleRequest textbookModuleRequest : moduleRequestList) {
            TeachingBookTemplate teachingBookTemplate = teachingBookTemplateService.getById(textbookModuleRequest.getId());
            TextbookModule textbookModule = new TextbookModule();
            textbookModule.setTextbookId(tb.getId());
            textbookModule.setTextbookModuleId(teachingBookTemplate.getId());
            textbookModuleService.insert(textbookModule);
            //课后练习
            if (teachingBookTemplate.getType().equals(TeachingBookConstant.TeachingBookTemplate.PRACTICE)) {
                TeachingBookPracticeRequest textbookPracticeRequest = textbookModuleRequest.getTeachingBookPracticeRequest();
                TextbookPractice practice = new TextbookPractice();
                practice.setTextbookId(tb.getId());
                practice.setTotalScore(textbookPracticeRequest.getTotalScore());
                practice.setUseTime(textbookPracticeRequest.getUseTime());
                textbookPracticeService.insert(practice);

                List<TeachingBookPracticeContentRequest> practiceContentRequests = textbookPracticeRequest.getContentDtos();
                if (!CollectionUtils.isEmpty(practiceContentRequests)) {
                    //备课练习内容
                    int j = 1;
                    for (TeachingBookPracticeContentRequest practiceContentRequest : practiceContentRequests) {
                        TextbookPracticeContent practiceContent = new TextbookPracticeContent();
                        practiceContent.setPracticeId(practice.getId());
                        practiceContent.setTextbookId(tb.getId());
                        practiceContent.setContentType(practiceContentRequest.getContentType());
                        practiceContent.setQuestionId(practiceContentRequest.getQuestionId());
                        practiceContent.setSubject(practiceContentRequest.getSubject());
                        practiceContent.setScore(practiceContentRequest.getScore());
                        practiceContent.setContent(practiceContentRequest.getContent());
                        practiceContent.setOrderNo(j);
                        practiceContent.setBlankLine(practiceContentRequest.getBlankLine());
                        textbookPracticeContentService.insert(practiceContent);

                        //插入试题id
                        if (!StringUtils.isEmpty(practiceContentRequest.getQuestionId())
                                && !StringUtils.isEmpty(practiceContentRequest.getSubject()) && !duplicateQuesIdMapValid.containsKey(practiceContentRequest.getQuestionId())) {
                            if (!duplicateQuesIdMapValid.containsKey(practiceContentRequest.getQuestionId())) {
                                QuestionDto question = practiceContentRequest.getQuestion();
                                duplicateQuesIdMapValid.put(practiceContentRequest.getQuestionId(), question);
                            }
                        }
                        j++;
                    }
                }
                TextbookModuleDetail detail = new TextbookModuleDetail();
                detail.setTextbookId(tb.getId());
                detail.setTextbookModuleId(textbookModuleRequest.getId());
                //课后练习
                detail.setContentType(7);
                detail.setResourceId(practice.getId());

                textbookModuleDetailService.insert(detail);
                continue;
            }
            List<TeachingBookModuleDetailRequest> moduleDetailRequests = textbookModuleRequest.getTeachingBookModuleDetailRequest();
            int i = 1;
            for (TeachingBookModuleDetailRequest moduleDetailRequest : moduleDetailRequests) {
                TextbookModuleDetail detail = new TextbookModuleDetail();
                detail.setTextbookId(tb.getId());
                detail.setTextbookModuleId(textbookModuleRequest.getId());
                detail.setContentType(moduleDetailRequest.getContentType());

                detail.setContent(moduleDetailRequest.getContent());
                detail.setMindMapImgPath(moduleDetailRequest.getMindMapImgPath());
                detail.setResourceId(moduleDetailRequest.getResourceId());
                detail.setSubject(moduleDetailRequest.getSubject());
                detail.setOrderNo(i);
                detail.setBlankLine(moduleDetailRequest.getBlankLine());

                textbookModuleDetailService.insert(detail);

                //如果为错题、变试题、普通试题、相似题 检查是否保存到本地题库
                if ((moduleDetailRequest.getContentType().equals(2) ||
                        moduleDetailRequest.getContentType().equals(3) ||
                        moduleDetailRequest.getContentType().equals(9)) &&
                        !StringUtils.isEmpty(moduleDetailRequest.getSubject()) && !duplicateQuesIdMapValid.containsKey(moduleDetailRequest.getResourceId())) {
                    QuestionDto question = moduleDetailRequest.getQuestion();
                    question.setSourceFrom(2);
                    duplicateQuesIdMapValid.put(moduleDetailRequest.getResourceId(), question);
                }
                i++;
            }
        }
        //同步箐优网试题到本地
        try {
            if (!MapUtils.isEmpty(duplicateQuesIdMapValid)) {
                for (String questionId : duplicateQuesIdMapValid.keySet()) {
                    questionService.addQuestion(duplicateQuesIdMapValid.get(questionId));
                }
            }
        } catch (Exception e) {
            log.error("保存备课同步试题异常：" + e.getMessage());
        }
        return tb.getId();
    }

    @Override
    public XhPage<Textbook> queryTextbookPage(XhPage page, QueryTextbookRequest request) {
        if (!StringUtils.isBlank(request.getChapterId())) {
            BookChapter chapter = bookChapterService.getById(request.getChapterId());
            request.setChapterPath(chapter.getPath());
        }
        //查询个人库 set creatorUserId
        if (request.getQueryType() != null && request.getQueryType().equals(2)) {
            String currentUserId = UserUtils.getCurrentUserId();
            request.setCreatorId(currentUserId);
        }
        if (request.getLongwenAreaId() == null && StringUtils.isBlank(request.getSchoolId())) {
            //查询自己所拥有地区数据权限的数据
            String currentUserId = UserUtils.getCurrentUserId();
            List<UserArea> userAreas = userAreaService.queryByUserId(currentUserId, 4);
            if (org.springframework.util.CollectionUtils.isEmpty(userAreas)) {
                return page;
            }
            List<String> schoolIds = userAreas.stream().map(item -> item.getAreaId().toString()).collect(Collectors.toList());
            request.setSchoolIds(schoolIds);
        }
        return this.dao.queryPage(page, request);
    }

    @Override
    public TextbookInfoDto getTeachingBookById(String id) {
        TextbookInfoDto textbookInfoDto = new TextbookInfoDto();
        TextbookDto textbookDto = this.getById(id, TextbookDto.class);
        if (textbookDto == null) {
            textbookDto = new TextbookDto();
            textbookDto.setUniqueKey(UUID.randomUUID().toString());
            List<TeachingBookTemplate> teachingBookTemplates = teachingBookTemplateService.queryAll();
            textbookInfoDto.setTeachingBookTemplates(teachingBookTemplates);
            return textbookInfoDto;
        }
        if (StringUtils.isBlank(textbookDto.getUniqueKey())) {
            textbookDto.setUniqueKey(UUID.randomUUID().toString());
        }
        textbookInfoDto.setTextbookDto(textbookDto);
        textbookInfoDto.setModules(textbookModuleService.queryTextbookModuleListByParentId(textbookDto.getId()));
        return textbookInfoDto;
    }

    /**
     * 准备条件
     *
     * @param request
     * @param qw
     */
    private QueryWrapper prepareParams(QueryTextbookRequest request, QueryWrapper qw) {
        //章节id
        if (!StringUtils.isBlank(request.getChapterId())) {
            qw.eq("chapter_id", request.getChapterId());
        }
        //年份
        if (request.getYear() != null) {
            qw.eq("year", request.getYear());
        }
        //适用阶段
        if (request.getApplyLevel() != null) {
            qw.like("apply_level", request.getApplyLevel().toString());
        }
        //排序方式
        if (!StringUtils.isBlank(request.getSortName()) && request.getSortIndex() != null) {
            boolean isAsc;
            if (request.getSortIndex() == 1) {
                isAsc = true;
            } else {
                isAsc = false;
            }
            String orderColumn = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, request.getSortName());
            qw.orderBy(true, isAsc, orderColumn);
        }
        return qw;
    }

    public void deleteTextbookByDetailById(String textbookId) {
        textbookModuleService.deleteByTextbookId(textbookId);
        textbookModuleDetailService.deleteByTextbookId(textbookId);
        textbookPracticeService.deleteByTextbookId(textbookId);
        textbookPracticeContentService.deleteByTextbookId(textbookId);
    }
}
